<?php
/**
 * 商品收藏服务层
 * @author maniac
 */
namespace app\common\service;

use app\common\model\GoodsCollect AS GoodsCollectModel;
use app\common\model\Goods AS GoodsModel;
use app\common\model\Stores;

class GoodsCollect extends Base
{
    /**
     * [取消]收藏商品
     * @param int $userId  用户 id
     * @param int $goodsId 商品 id
     */
    public function collect($userId, $goodsId,$type=0)
    {
        $where = [
            'userid'   => $userId,
            'goods_id' => $goodsId,
            'type'=>$type
        ];
        $info  = GoodsCollectModel::field('id,goods_id')->where($where)->find();
        $goods = GoodsModel::field('id,collect_nums')->where('id', $goodsId)->find();
        if ($info) {
            GoodsCollectModel::destroy($info['id']);
            $goods->collect_nums = ['dec', 1];
            $action = '取消收藏';
        } else {
            GoodsCollectModel::create($where);
            $goods->collect_nums = ['inc', 1];
            $action = '收藏';
        }
        $goods->save();
        return $action.'成功';
    }
    
    /**
     * 用户是否收藏过指定商品
     * @param  int  $userId  用户 id
     * @param  int  $goodsId 商品 id
     * @return boolean
     */
    public function isCollect($where,$type = 0)
    {
        $info = GoodsCollectModel::field('id')->where($where)->fetchSql(false)->find();

        return $info ? true : false;
    }
    
    /**
     * 移除
     * @param int $id 收藏商品表主键
     */
    public function deleteCollect($id)
    {
        if (!$id) {
            exception('请选择要移除的商品');
        }
        $id = explode(',',$id);
        foreach ($id as $k =>$v){
			$info = GoodsCollectModel::field('id,goods_id,type')->where('id', $v)->find();
			if (!$info) {
				exception('收藏的商品不存在');
			}

			if($info['type']==1){
				$goods=Stores::field('id,collect_nums')->where('id',$info['goods_id'])->find();
			}else{
				$goods = GoodsModel::field('id,collect_nums')->where('id', $info['goods_id'])->find();
			}
			if ($info) {
				GoodsCollectModel::destroy($v);
				if($info['type']==1){
					$goods->collect_nums = ['dec', 1];
					$goods->save();
				}else{
					$goods->collect_nums = ['dec', 1];
					$goods->save();
				}
			}
		}
        return 1;

    }
}
